<?php

#namespace Giocondo;

# xhtml -- Facilities to build XHTML elements with attributes.
class XHtml {
	# Content must be NULL for an empty element.
	static public function element($name, $content = NULL, $attributes = array()) {
		$empty = is_null($content); # empty element?
		self::start_tag($name, $attributes, $empty);

		if (! $empty) {
			# TODO: there was a htmlspecialchars($content, ENT_NOQUOTES) here.
			# It should not be necessary because it is responsibility of the callee
			# to call the appropriate String::method.
			echo $content;
			self::end_tag($name);
		}
	}

	static public function start_tag($name, $attributes = array(), $empty = FALSE) {
		# We assume name is all lowercase as required by XHTML specs.
		echo "<$name";
		foreach ($attributes as $attribute => $value) {
			# Transform attribute values for some special attributes.
			# Put most common attributes first to optimize.
			# TODO: some statistical data should be available to reorder cases.
			switch (strtolower($attribute)) {
				case 'id':
					$value = "w$value";
				break;

				case 'value':
					if ($value === '') {
						continue 2;
					}
				break;

				case 'maxlength':
				case 'size':
					if ($value === -1) {
						continue 2;
					}
				break;

				case 'readonly':
					if ($value === 0) {
						$value = 'readonly';
					} else {
						continue 2;
					}
				break;

				case 'disabled':
					if ($value === 0) {
						$value = 'disabled';
					} else {
						continue 2;
					}
				break;
			}

			printf(' %s="%s"', $attribute, String::attribute($value));
		}

		echo $empty ? ' />' : '>';
	}

	static public function end_tag($name) {
			printf('</%s>', $name);
	}
}

# End of file
# vim: set ts=2 sw=2 noet:
?>
